// client.cpp
#include "client.h"

Client::Client(QObject *parent) : QObject(parent)
{
    socket = new QTcpSocket(this);
    
    connect(socket, &QTcpSocket::connected, this, &Client::onConnected);
    connect(socket, &QTcpSocket::disconnected, this, &Client::onDisconnected);
    connect(socket, &QTcpSocket::readyRead, this, &Client::onReadyRead);
}

void Client::connectToServer(const QString &host, quint16 port)
{
    socket->connectToHost(host, port);
}

void Client::onConnected()
{
    qDebug() << "Connected to server!";
    
    // 发送测试消息
    sendMessage("Hello from client!");
}

void Client::onDisconnected()
{
    qDebug() << "Disconnected from server!";
}

void Client::onReadyRead()
{
    QByteArray data = socket->readAll();
    qDebug() << "Received from server:" << QString(data);
}

void Client::sendMessage(const QString &message)
{
    if (socket->state() == QTcpSocket::ConnectedState) {
        socket->write(message.toUtf8());
        socket->flush();
    }
}

// client.cpp 中添加
void Client::disconnectFromServer()
{
    if (socket && socket->state() == QTcpSocket::ConnectedState) {
        socket->disconnectFromHost(); // 优雅断开连接
        // 或者使用 socket->abort(); 立即断开
    }
}
